<?php
require_once 'config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    $email = trim($_POST['email']);
    
    if (empty($username) || empty($password) || empty($email)) {
        $error = "所有字段都必须填写";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "无效的邮箱地址";
    } else {
        $stmt = $conn->prepare("SELECT id FROM users WHERE username = ? AND is_verified = 1");
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $stmt->store_result();
        
        if ($stmt->num_rows > 0) {
            $error = "该用户名已被注册";
        } else {
            $stmt = $conn->prepare("SELECT id FROM users WHERE email = ? AND is_verified = 1");
            $stmt->bind_param("s", $email);
            $stmt->execute();
            $stmt->store_result();
            
            if ($stmt->num_rows > 0) {
                $error = "该邮箱已被注册";
            } else {
                $stmt = $conn->prepare("DELETE FROM users WHERE (username = ? OR email = ?) AND is_verified = 0 AND registration_time < DATE_SUB(NOW(), INTERVAL 1 HOUR)");
                $stmt->bind_param("ss", $username, $email);
                $stmt->execute();
                
                $verification_code = hash('sha256', $username . time());
                
                $password_hash = password_hash($password, PASSWORD_DEFAULT);
                
                $stmt = $conn->prepare("INSERT INTO users (username, password, email, verification_code) VALUES (?, ?, ?, ?)");
                $stmt->bind_param("ssss", $username, $password_hash, $email, $verification_code);
                
                if ($stmt->execute()) {
                    $verification_link = BASE_URL . "verify.php?user=" . urlencode($username) . "&code=" . $verification_code;
                    
                    $subject = "请激活您的账户";
                    $message = "尊敬的 " . $username . ",\n\n";
                    $message .= "感谢您注册我们的服务。请点击以下链接激活您的账户：\n";
                    $message .= $verification_link . "\n\n";
                    $message .= "如果您没有注册，请忽略此邮件。\n";
                    $message .= "此链接将在1小时后失效。\n\n";
                    $message .= "此致\n敬礼";
                    
                    $headers = "From: " . FROM_NAME . " <" . FROM_EMAIL . ">\r\n";
                    $headers .= "Reply-To: " . FROM_EMAIL . "\r\n";
                    $headers .= "X-Mailer: PHP/" . phpversion();
                    
                    if (mail($email, $subject, $message, $headers)) {
                        $success = "注册成功！请检查您的邮箱以激活账户。";
                    } else {
                        $error = "无法发送验证邮件，请稍后再试。";
                        $conn->rollback();
                    }
                } else {
                    $error = "注册失败，请稍后再试。";
                }
            }
        }
        $stmt->close();
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>用户注册</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 500px; margin: 0 auto; padding: 20px; }
        .error { color: red; }
        .success { color: green; }
        input { display: block; width: 100%; padding: 8px; margin: 10px 0; box-sizing: border-box; }
        button { background-color: #4CAF50; color: white; padding: 10px 15px; border: none; cursor: pointer; }
        button:hover { background-color: #45a049; }
    </style>
</head>
<body>
    <h2>用户注册</h2>
    <?php if (isset($error)): ?>
        <p class="error"><?php echo htmlspecialchars($error); ?></p>
    <?php elseif (isset($success)): ?>
        <p class="success"><?php echo htmlspecialchars($success); ?></p>
    <?php endif; ?>
    
    <form method="post">
        <label for="username">昵称:</label>
        <input type="text" id="username" name="username" required>
        
        <label for="password">口令:</label>
        <input type="password" id="password" name="password" required>
        
        <label for="email">邮箱:</label>
        <input type="email" id="email" name="email" required>
        
        <button type="submit">注册</button>
    </form>
</body>
</html>